/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

abstract class Event_ {
  abstract subscribe<T = unknown>(event: string, cb: (data?: T) => void): void;
  abstract unsubscribe<T = unknown>(event: string, cb?: (data?: T) => void): void;
  abstract publish<T = unknown>(event: string, data?: T): void;
  abstract once<T = unknown>(event: string, cb: (data?: T) => void): void;
}

class EventEmitter extends Event_ {
  private events: Record<string, Array<{ cb: (data?: any) => void, once?: boolean }>> = {};
  subscribe<T = unknown>(event: string, cb: (data?: T) => void, once: boolean = false): void {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push({ cb, once })
  }
  once<T = unknown>(event: string, cb: (data?: T) => void): void {
    this.subscribe(event, cb, true)
  }
  unsubscribe<T = unknown>(event: string, cb?: (data?: T) => void): void {
    if (!this.events[event]) return;
    if (cb) {
      this.events[event] = this.events[event].filter(item => item.cb !== cb);
    } else {
      delete this.events[event];
    }
  }
  publish<T = unknown>(event: string, data?: T): void {
    if (!this.events[event]) return;
    [...this.events[event]].forEach(({ cb, once }) => {
      cb(data);
      if (once) {
        this.unsubscribe(event, cb)
      }
    })
  }
}

export const emitter = new EventEmitter();
